<template>
  <div class="app-container">
    <Header></Header>
    <Goods
      v-for="item in list"
      :key="item.id"
      :id="item.id"
      :title="item.goods_name"
      :pic="item.goods_img"
      :state="item.goods_state"
      :count="item.goods_count"
      :price="item.goods_price"
      @state-change="GetNewState"
    ></Goods>
    <Footer
      :isFull="fullState"
      :amount="amt"
      :num="total"
      :all="total"
      @change-Full="getFullChange"
    ></Footer>
  </div>
</template>

<script>
// 导入 axios 请求库
import axios from "axios";
// 导入需要的组件
import Header from "@/components/Header/Header.vue";
import Goods from "@/components/Goods/Goods.vue";
import Footer from "@/components/Footer/Footer.vue";

import bus from "@/components/eventBus.js";
export default {
  data() {
    return {
      // 储存购物车的列表数据，默认为空数组
      list: [],
    };
  },
  methods: {
    // 封装列表数据的方法
    async initCartList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      // console.log(res);
      if (res.status === 200) {
        this.list = res.list;
      }
    },
    GetNewState(val) {
      this.list.some((item) => {
        if (item.id === val.id) {
          item.goods_state = val.value;
          // 结束循环
          return true;
        }
      });
    },
    getFullChange(val) {
      // 把所有的商品都勾选
      this.list.forEach((item) => (item.goods_state = val));
    },
  },
  // 计算属性
  computed: {
    // 动态计算出全选的状态是 true 还是 false
    fullState() {
      return this.list.every((item) => item.goods_state === true);
    },
    // 已勾选商品的总价格
    amt() {
      // 1. 先用 filter过滤
      // 2. 再用 reduce累加
      return this.list
        .filter((item) => item.goods_state)
        .reduce((total, item) => {
          return (total += item.goods_count * item.goods_price);
        }, 0);
    },
    // 已勾选商品的总数量
    total() {
      return this.list
        .filter((item) => item.goods_state)
        .reduce((i, item) => {
          return (i += item.goods_count);
        }, 0);
    },
  },
  created() {
    // 调用请求数据的方法
    this.initCartList();
    // 只要请求回来的数据 在页面渲染期间要用到，必须放到data里面转存

    bus.$on("share", (val) => {
      this.list.some((item) => {
        if (item.id === val.id) {
          item.goods_count = val.value;
          return true;
        }
      });
    });
  },
  components: {
    Header,
    Goods,
    Footer,
  },
};
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
